<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\analysis\data\material\stat;

use app\enum\AnalysisEnum;
use app\model\mongo\MongoStatModel;
use think\facade\Cache;

trait MonthStatTrait
{
    /**
     * @var null|MongoStatModel 汇总模型
     */
    protected ?MongoStatModel $log;

    /**
     * @var int 任务类型
     */
    protected int $taskType = 0;

    /**
     * 设置汇总.
     */
    public function setStat(): bool
    {
        if (! $this->setMonthStat()) {
            return false;
        }
        if (! $this->setAreaMonthQueue()) {
            return self::setError('设置月汇总失败');
        }
        return $this->finishLog();
    }

    /**
     * 设置月汇总数据.
     */
    private function setMonthStat(): bool
    {
        $model = $this->getMonthStatModel();
        if (! $model instanceof MongoStatModel) {
            return self::setError('未知素材月汇总模型');
        }
        if (! $model->getKey()) {
            $data = [
                'stat_month' => $this->log->getAttr('stat_month'),
                'signature' => $this->log->getAttr('signature'),
                'area_id' => $this->log->getAttr('area_id'),
                'qq' => ['cost' => 0],
                'oe' => ['cost' => 0],
                'ks' => ['cost' => 0],
            ];
        } else {
            $data = [];
        }
        $data = $this->getMonthStatField($data);
        $model->setAttrs($data);
        if (! $model->save()) {
            return self::setError('保存素材日维度汇总失败');
        }
        return true;
    }

    /**
     * 设置汇总完成.
     * @return true
     */
    private function setAreaMonthQueue(): bool
    {
        $redis = Cache::store('redis')->handler();
        $key = AnalysisEnum::TASK_QUEUE_LIST['area_month_stat'] ?? '';
        if ($key) {
            $value = json_encode([$this->log->getAttr('stat_month'), $this->log->getAttr('area_id'), $this->taskType]);
            $field = md5($value);
            if (! $redis->hExists($key, $field)) {
                $redis->hSetnx($key, $field, $value);
            }
        }
        return true;
    }

    /**
     * 设置日志完成.
     */
    private function finishLog(): bool
    {
        $this->log->setAttr('is_change', MongoStatModel::IS_CHANGE_NO);
        return $this->log->save();
    }
}
